package com.cooksys.film_rental.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cooksys.film_rental.dao.PaymentDao;
import com.cooksys.film_rental.model.City;
import com.cooksys.film_rental.model.Customer;
import com.cooksys.film_rental.model.Payment;
import com.cooksys.film_rental.model.Rental;
import com.cooksys.film_rental.model.Staff;

@Repository("PaymentDao")
@Transactional
public class PaymentDaoImpl implements PaymentDao {

	@Autowired(required = true)
	private SessionFactory sessionFactory;

	/**
	 * 
	 * @return the current session from the internal {@link SessionFactory}
	 */
	public Session currentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public Payment getPaymentByPaymentId(Short paymentId) {
		Session session = currentSession();

		// returns a record from the PAYMENT table as an Payment object
		// based on the given paymentId, the table's primary key
		String hql = "from Payment p where p.paymentId = :paymentId";

		Query query = session.createQuery(hql);
		query.setShort("paymentId", paymentId);

		return (Payment) query.list().get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Payment> searchPaymentsByStaff(Staff staff) {
		Session session = currentSession();

		String hql = "from Payment p where p.staff = :staff";
		Query query = session.createQuery(hql);
		query.setEntity("staff", staff);

		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Payment> searchPaymentsByCustomer(Customer customer) {
		Session session = currentSession();

		String hql = "from Payment p where p.customer = :customer";
		Query query = session.createQuery(hql);
		query.setEntity("customer", customer);

		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Payment> searchPaymentsByRental(Rental rental) {
		Session session = currentSession();

		String hql = "from Payment p where p.rental = :rental";
		Query query = session.createQuery(hql);
		query.setEntity("rental", rental);

		return query.list();
	}

	@Override
	public Payment save(Payment payment) {
		Session session = currentSession();
		Serializable id = session.save(payment);
		return (Payment) session.get(Payment.class, id);
	}

}
